package com.semidata.trp.business.http;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.QueryStringDecoder;

import java.net.URLDecoder;

import com.semidata.rtd.core.http.server.AbstractDispatchHandler;
import com.semidata.rtd.core.http.server.HttpSession;
import com.semidata.rtd.core.service.ServiceManager;
import com.semidata.trp.business.data.DataService;

public class RegisterHttpHandler extends AbstractDispatchHandler {

    public RegisterHttpHandler(ChannelHandlerContext ctx, HttpRequest request) {
        super(ctx, request);
    }

    @SuppressWarnings("deprecation")
    @Override
    public void handle(HttpSession session) {
        QueryStringDecoder decoder = new QueryStringDecoder(session.getRequest().getUri());
        try {
            String type = decoder.parameters().get("type").get(0).toUpperCase();
            if (type.endsWith("DECISION")) {
                String name = decoder.parameters().get("name").get(0);
                boolean active = Boolean.parseBoolean(decoder.parameters().get("active").get(0));
                String businessUrl = decoder.parameters().get("business_url").get(0);
                String budgetUrl = decoder.parameters().get("budget_url").get(0);
                String reportUrl = decoder.parameters().get("report_url").get(0);
                businessUrl = URLDecoder.decode(businessUrl);
                budgetUrl = URLDecoder.decode(budgetUrl);
                reportUrl = URLDecoder.decode(reportUrl);
            
                DataService service = ServiceManager.getService(DataService.class);
                service.updateDecisionServer(name, businessUrl, budgetUrl, reportUrl, active);
               
            } else if (type.endsWith("MONITOR")) {
                String name = decoder.parameters().get("name").get(0);
                boolean active = Boolean.parseBoolean(decoder.parameters().get("active").get(0));
                DataService service = ServiceManager.getService(DataService.class);
                service.updateMonitorServer(name, active);
            } else {
                throw new Exception("type " + type + " not supported");
            }

            session.getResponse().end();

        } catch (Exception e) {
            e.printStackTrace();
            session.getResponse().error();
        }

    }


}
